package com.easyaccount.service;

import com.easyaccount.bean.LoginUser;
import com.easyaccount.commons.CommonResp;
import com.easyaccount.commons.Constant;
import com.easyaccount.commons.TablePage;
import com.easyaccount.dao.BillMapper;
import com.easyaccount.dao.DailyMapper;
import com.easyaccount.dao.UserRoleMapper;
import com.easyaccount.exception.BizException;
import com.easyaccount.model.*;
import com.easyaccount.util.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BillService {

    @Resource
    private BusibessInfoService busibessInfoService;
    @Resource
    private TrafficService trafficService;
    @Resource
    private HotelService hotelService;
    @Resource
    private OtherService otherService;
    @Resource
    private BillImgService billImgService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private DailyMapper dailyMapper;
    @Resource
    private BillMapper billMapper;

    @Transactional(rollbackFor = Exception.class)
    public CommonResp saveDaily(MultipartFile[] file, List<Daily> dailies,
                                Double total, HttpSession session, int category){
        LoginUser user = (LoginUser) session.getAttribute("user");

        Bill bill = new Bill();
        bill.setProgress(getProgress(user.getId()));
        bill.setCategory(category);
        bill.setUserId(user.getId());
        bill.setTotal(total);
        bill.setIconType("layui-bg-cyan");
        Date date = new Date();
        bill.setCreateTime(date);
        bill.setCode(date.getTime() / 1000 + "");
        billMapper.insertSelective(bill);

        dailies.forEach(daily -> {
            daily.setBillId(bill.getBillId());
        });

        dailyMapper.insertBacth(dailies);
        if (file != null && file.length > 0) saveImg(file,bill);
        return CommonResp.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public CommonResp saveBusiness(MultipartFile[] file, BusinessInfo bizInfos, List<Traffic> traffics,
                                   List<Hotel> hotels, List<Other> others, Double total, HttpSession session, int category) {
        LoginUser user = (LoginUser) session.getAttribute("user");

        Bill bill = new Bill();
        bill.setProgress(getProgress(user.getId()));
        bill.setCategory(category);
        bill.setUserId(user.getId());
        bill.setIconType("layui-bg-cyan");
        bill.setTotal(total);
        Date date = new Date();
        bill.setCreateTime(date);
        bill.setCode(date.getTime() / 1000 + "");
        billMapper.insertSelective(bill);

        traffics.forEach(item -> {
            item.setBillId(bill.getBillId());
            item.setCategory(Constant.BUSINESS_CATE_TRAFFIC);
        });
        hotels.forEach(item -> {
            item.setBillId(bill.getBillId());
            item.setCategory(Constant.BUSINESS_CATE_HOTEL);
        });
        others.forEach(item -> {
            item.setBillId(bill.getBillId());
            item.setCategory(Constant.BUSINESS_CATE_OTHER);
        });

        try {
            bizInfos.setBillId(bill.getBillId());
            busibessInfoService.save(bizInfos);
            if (traffics.size() > 0) trafficService.save(traffics);
            if (hotels.size() > 0) hotelService.save(hotels);
            if (others.size() > 0) otherService.save(others);
            if (file != null && file.length > 0) saveImg(file,bill);
        }catch (Exception e){
            throw new BizException("服务异常，申请失败",444);
        }

        return CommonResp.success();
    }


    private int getProgress(int userId){
        UserRole userRole = userRoleMapper.selectByUserId(userId);
        if(userRole.getRoleId() == 2){
            return Constant.PROGRESS_CW_CHECKED;
        }else if(userRole.getRoleId() == 3){
            return Constant.PROGRESS_COMMIT;
        }else{
            return Constant.PROGRESS_COMMIT;
        }
    }

    private void saveImg(MultipartFile[] file,Bill bill){
        int index = 1;
        String code = bill.getCode();
        List<BillImg> list = new ArrayList<>();
        for (MultipartFile item : file) {
            String originalFilename = item.getOriginalFilename();
            System.out.println(item.getName());
            System.out.println(originalFilename);
            String suffix = originalFilename.split("\\.")[1];
            String imgName = code + "_" + index + "." + suffix;
            String filePath = Constant.UPLOAD_FILE_PATH + imgName;
            try {
                InputStream in = item.getInputStream();
                FileUtils.write(filePath,in);

                BillImg billImg = new BillImg();
                billImg.setBillCode(bill.getCode());
                billImg.setImgName(imgName);
                list.add(billImg);

                index++;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        billImgService.save(list);
    }


}
